<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  getTrademark,
  addOrUpdateTrademark,
  deleteTrademark,
} from '@/api/product/trademark/index.ts'
import {
  trademarkResponseData,
  trademark,
  Records,
} from '@/api/product/trademark/type.ts'
import { ElMessage, UploadProps } from 'element-plus'
const trademarkData = ref<Records>([])
let total = ref<number>(100)
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
const dialogVisible = ref<boolean>(false)
const formRef = ref()
let trademarkFormData = reactive<trademark>({
  tmName: '',
  logoUrl: '',
})
onMounted(() => {
  getTrademarkData()
})
const validatorTmName = (_: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    //校验未通过返回的错误的提示信息
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
const validatorLogoUrl = (_: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
const getTrademarkData = async (cPage = 1) => {
  currentPage.value = cPage
  let res: trademarkResponseData = await getTrademark(
    currentPage.value,
    pageSize.value,
  )
  if (res.code == 200) {
    trademarkData.value = res.data.records
    total.value = res.data.total
  }
}
const handleSizeChange = () => {
  getTrademarkData()
}
const addTrademark = () => {
  dialogVisible.value = true
  trademarkFormData.id = 0
  trademarkFormData.tmName = ''
  trademarkFormData.logoUrl = ''
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkFormData.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif' ||
    rawFile.type == 'image/webp'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必jpeg|png|gif',
    })
    return false
  }
}
const cancelDialog = () => {
  dialogVisible.value = false
}
const verifyDialog = async () => {
  //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
  await formRef.value.validate()
  let res = await addOrUpdateTrademark(trademarkFormData)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: trademarkFormData.id ? '修改成功' : '添加成功',
    })
    dialogVisible.value = false
    await getTrademarkData(trademarkFormData.id ? currentPage.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademarkFormData.id ? '修改失败' : '添加失败',
    })
    dialogVisible.value = false
  }
}
const editTrademark = (row: trademark) => {
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  dialogVisible.value = true
  //ES6语法合并对象
  Object.assign(trademarkFormData, row)
}
const deleteTrademarkById = async (row: any) => {
  let res: any = await deleteTrademark(row.id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getTrademarkData(
      trademarkData.value.length > 1
        ? currentPage.value
        : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
</script>

<template>
  <el-card>
    <el-button
      type="primary"
      icon="Plus"
      plain
      @click="addTrademark"
      v-has="`btn.Trademark.add`"
    >
      添加品牌
    </el-button>
    <el-table :data="trademarkData" style="margin: 10px 0" border>
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #default="scope">
          <img
            :src="scope.row.logoUrl"
            alt=""
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #default="scope">
          <el-button
            type="warning"
            icon="Edit"
            plain
            @click="editTrademark(scope.row)"
            v-has="`btn.Trademark.update`"
          ></el-button>
          <el-popconfirm
            :title="`你确定删除'${scope.row.tmName}'吗？`"
            @confirm="deleteTrademarkById(scope.row)"
            width="250"
          >
            <template #reference>
              <el-button
                type="danger"
                icon="Delete"
                plain
                v-has="`btn.Trademark.remove`"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15]"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="Number(total)"
      @size-change="handleSizeChange"
      @current-change="getTrademarkData"
      :pager-count="7"
    />
  </el-card>

  <el-dialog
    v-model="dialogVisible"
    :title="trademarkFormData.id ? '修改品牌' : '添加品牌'"
    width="50%"
  >
    <el-form
      ref="formRef"
      :rules="rules"
      :model="trademarkFormData"
      style="width: 80%"
      label-width="100px"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          v-model="trademarkFormData.tmName"
          type="text"
          placeholder="请输入品牌名称"
        />
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkFormData.logoUrl"
            :src="trademarkFormData.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="verifyDialog">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
